package com.ali.ttt.netty.common.handler;

import com.ali.ttt.core.cocurrent.FutureTaskScheduler;
import com.ali.ttt.netty.common.domain.Message;
import com.ali.ttt.netty.common.listener.MessageListenerProcessor;
import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@Slf4j
@Service
@ChannelHandler.Sharable
public class InMessageHandler extends SimpleChannelInboundHandler<Object> {

    @Resource
    private MessageListenerProcessor messageListenerProcessor;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        String message = ((ByteBuf)msg).toString(StandardCharsets.UTF_8);
        ctx.writeAndFlush(Unpooled.copiedBuffer(JSONObject.toJSONString(msg), StandardCharsets.UTF_8));
        Message entity = JSONObject.parseObject(message, Message.class);
        FutureTaskScheduler.add(()-> messageListenerProcessor.processMessage(entity,ctx));
    }
}
